//
//  MainTableViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-5-20.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "MainViewController.h"
#import <MMDrawerController/MMDrawerBarButtonItem.h>
#import <UIViewController+MMDrawerController.h>
#import "MenuViewController.h"
#import "SNSCropImageViewController.h"
#import "SNSPhotoFilterViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>


#import "SNSCommentViewController.h"

#import "MJRefresh.h"

#import "SNSMessageViewCell.h"
#import "SNSPostViewCell.h"

#import <MWPhotoBrowser.h>
#import <UIProgressView+AFNetworking.h>

#import "NetworkAccessManager.h"

#import "UIAlertView+Kirinrin.h"
#import "SNSTextViewController.h"
#import "SNSPostModel.h"

#import "SNSSendPostDelegate.h"

#define kNoticeCell     @"NoticeCell"
#define kCheckCell      @"CheckOnCell"
#define kScoreCell      @"ScoreCell"
#define kIMCell         @"IMCell"
#define kRestCell       @"RestCell"


#define kMessageKey     @"messages"
#define kPostKey        @"posts"

#define kMaxReturnCount  5

#define kCropPhotoSize      320


/**
 *  帖子显示类型的cellID
 */
#define kPostCellText           @"PostCellText"
#define kPostCellTextPlusOne    @"PostCellTextPlusOne"
#define kPostCellTextComment    @"PostCellTextComment"
#define kPostCellTextAll        @"PostCellTextAll"

#define kPostCellShort      @"PostCellShort"
#define kPostCellPlusOne    @"PostCellPlusOne"
#define kPostCellAll        @"PostCellAll"
#define kPostCellNoPlusOne  @"PostCellNoPlusOne"


typedef NS_ENUM(NSUInteger, SNSDisplayType){
    SNSPostShort,
    SNSPostPlusOne,
    SNSPostNoPlusOne,
    SNSPostAll,
};

@interface MainViewController ()<UITableViewDataSource, UITableViewDelegate, MWPhotoBrowserDelegate, UIActionSheetDelegate, UIImagePickerControllerDelegate, UINavigationControllerDelegate, SNSPostViewDelegate, SNSCommentViewControllerDelegate, SNSSendPostDelegate,MJRefreshBaseViewDelegate>

@property (weak, nonatomic) IBOutlet UITableView *tableView;

@property (nonatomic, strong)NSDictionary *data;

@property (strong, nonatomic) SNSPostViewCell *prototypeCellText;
@property (strong, nonatomic) SNSPostViewCell *prototypeCellTextPlusOne;
@property (strong, nonatomic) SNSPostViewCell *prototypeCellTextComment;
@property (strong, nonatomic) SNSPostViewCell *prototypeCellTextAll;

@property (strong, nonatomic) SNSPostViewCell *prototypeCell;
@property (strong, nonatomic) SNSPostViewCell *prototypeCellNoPlusOne;

@property (nonatomic, weak) MJRefreshFooterView *footerMain;
@property (nonatomic, weak) MJRefreshHeaderView *headerMain;

@end


@implementation MainViewController{
    MWPhoto *displayPhoto;
}


- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //    UIBarButtonItem *cameraButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(pickOrShootPhoto:)];
    //    [self.navigationItem setRightBarButtonItem:cameraButton];
    
    //    self.title = @"橡树班趣事";
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.title = [NSString stringWithFormat:@"%@", self.appDelegate.user[@"kClassName"]];
    
    MJRefreshHeaderView *header = [MJRefreshHeaderView header];
    header.scrollView = self.tableView;
    header.delegate = self;
    [header beginRefreshing];
    self.headerMain = header;
    
    MJRefreshFooterView *footer = [MJRefreshFooterView footer];
    footer.scrollView = self.tableView;
    footer.delegate = self;
    self.footerMain = footer;
    
//    [self.tableView addHeaderWithCallback:^{
//        [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypeAll isBackground:NO goTop:NO];
//    }];
//    [self.tableView addFooterWithCallback:^{
//        if (self.data[kPostKey]) {
//            NSArray *postList = self.data[kPostKey];
//            SNSPostModel *lastPost = [postList lastObject];
//            [self loadSNSData:lastPost.no :kMaxReturnCount snsType:SNSTypePost isBackground:NO goTop:NO];
//        }else{
//            [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypePost isBackground:NO goTop:NO];
//        }
//        
//    }];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellText" bundle:nil] forCellReuseIdentifier:kPostCellText];
    self.prototypeCellText = [self.tableView dequeueReusableCellWithIdentifier:kPostCellText];
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellTextPlusOne" bundle:nil] forCellReuseIdentifier:kPostCellTextPlusOne];
    self.prototypeCellTextPlusOne = [self.tableView dequeueReusableCellWithIdentifier:kPostCellTextPlusOne];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellTextComment" bundle:nil] forCellReuseIdentifier:kPostCellTextComment];
    self.prototypeCellTextComment = [self.tableView dequeueReusableCellWithIdentifier:kPostCellTextComment];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellTextAll" bundle:nil] forCellReuseIdentifier:kPostCellTextAll];
    self.prototypeCellTextAll = [self.tableView dequeueReusableCellWithIdentifier:kPostCellTextAll];
    
    
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellShort" bundle:nil] forCellReuseIdentifier:kPostCellShort];
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellPlusOne" bundle:nil] forCellReuseIdentifier:kPostCellPlusOne];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCell" bundle:nil] forCellReuseIdentifier:kPostCellAll];
    self.prototypeCell = [self.tableView dequeueReusableCellWithIdentifier:kPostCellAll];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"SNSPostViewCellWithoutPlusOne" bundle:nil] forCellReuseIdentifier:kPostCellNoPlusOne];
    self.prototypeCellNoPlusOne = [self.tableView dequeueReusableCellWithIdentifier:kPostCellNoPlusOne];
    
    
    
    [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypeAll isBackground:NO goTop:NO];
}

-(void)dealloc
{
    [self.headerMain free];
    [self.footerMain free];
}

-(void)refreshViewBeginRefreshing:(MJRefreshBaseView *)refreshView
{
    if ([refreshView isKindOfClass:[MJRefreshHeaderView class]]) {
        [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypeAll isBackground:NO goTop:NO];
        [self.headerMain endRefreshing];
    } else {
        if (self.data[kPostKey]) {
            NSArray *postList = self.data[kPostKey];
            SNSPostModel *lastPost = [postList lastObject];
            [self loadSNSData:lastPost.no :kMaxReturnCount snsType:SNSTypePost isBackground:NO goTop:NO];
        }else{
            [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypePost isBackground:NO goTop:NO];
        }
        [self.footerMain endRefreshing];
    }

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)viewWillAppear:(BOOL)animated{
    
}

- (void)loadSNSData:(NSUInteger)firstReturnCount :(NSUInteger)maxReturnCount snsType:(SNSWSType)snsType isBackground:(BOOL)background  goTop:(BOOL)goTop{
    NSString *uriString = @"Messages.json";
    
    NSMutableDictionary *parameters = [[NSMutableDictionary alloc]init];
    [parameters setObject:self.appDelegate.accessKey forKey:@"key"];
    [parameters setObject:@(firstReturnCount) forKey:@"firstReturnCount"];
    [parameters setObject:@(maxReturnCount) forKey:@"maxReturnCount"];
    if (snsType != SNSTypeAll) {
        [parameters setObject:@(snsType) forKey:@"messageType"];
    }
    
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
//        NSIndexPath *lastIndexPath = [NSIndexPath indexPathForRow:[[self.data objectForKey:kPostKey] count]-1 inSection:1];
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0 && ![responseObject[@"data"]isEqual:[NSNull null]]) {
            
            
            
            if (firstReturnCount == 0) {
                [_data[kMessageKey] removeAllObjects];
                [_data[kPostKey] removeAllObjects];
            }
            
            
            int returnCount = 0;
            
            if (responseObject[@"data"]) {
                
                if (snsType == SNSTypeAll) {
                    if ([responseObject[@"data"] objectForKey:kMessageKey] && ![[responseObject[@"data"] objectForKey:kMessageKey] isEqual:[NSNull null]]) {
                        [_data[kMessageKey] addObjectsFromArray:responseObject[@"data"][kMessageKey] ];
                    }
                    if ([responseObject[@"data"]objectForKey:kPostKey]) {
                        for (NSDictionary *dict in responseObject[@"data"][kPostKey]) {
                            [_data[kPostKey]addObject:[[SNSPostModel alloc]initWithDictionary:dict]];
                        };
                        
                        returnCount = [[responseObject[@"data"]objectForKey:kPostKey] count];
                    }
                }else if (snsType == SNSTypeMessage && ![responseObject[@"data"] isEqual:[NSNull null]]){
                    [_data[kMessageKey] addObjectsFromArray:responseObject[@"data"]];
                }else if (snsType == SNSTypePost && ![responseObject[@"data"]isEqual:[NSNull null]]){
                    for (NSDictionary *dict in responseObject[@"data"]) {
                        [_data[kPostKey]addObject:[[SNSPostModel alloc]initWithDictionary:dict]];
                    };
                    returnCount = [responseObject[@"data"] count];
                }
            }
            
            
            
            [self.tableView reloadData];
            if (goTop) {
                [self.tableView setContentOffset:CGPointZero animated:YES];
            }
            if (!background) {
                if (snsType == SNSTypeAll) {
//                    [self.tableView headerEndRefreshing];
                    [self.headerMain endRefreshing];
                }else{
//                    [self.tableView footerEndRefreshing];
                    [self.footerMain endRefreshing];
//                    [self.tableView scrollToRowAtIndexPath:lastIndexPath atScrollPosition:UITableViewScrollPositionBottom animated:NO];
                }
            }

        }else{
            if (!background) {
                if (snsType == SNSTypeAll) {
//                    [self.tableView headerEndRefreshing];
                    [self.headerMain endRefreshing];
                }else{
//                    [self.tableView footerEndRefreshing];
                    [self.footerMain endRefreshing];
                }
            }
            if (resultCode != 0) {
                [UIAlertView alertWithRemoteError:resultCode];

            }
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if ([self.data[kPostKey] count] == 0) {
        if (section == 0) {
            return [[self.data objectForKey:kMessageKey] count];
        }else{
            return 1;
        }
    }else{
        if (section == 0) {
            return [[self.data objectForKey:kMessageKey] count];
        }else{
            return [[self.data objectForKey:kPostKey] count];
        }
    }
    
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
    SNSMessageViewCell *cell;
    if (indexPath.section == 0) {
        NSDictionary *messageData = self.data[kMessageKey][indexPath.row];
        switch ([messageData[@"type"] intValue]) {
            case SNSMessageNotice:
                cell = [tableView dequeueReusableCellWithIdentifier:kNoticeCell];
                break;
            case SNSMessageCheckOn:
                cell = [tableView dequeueReusableCellWithIdentifier:kCheckCell];
                break;
            case SNSMessageScore:
                cell = [tableView dequeueReusableCellWithIdentifier:kScoreCell];
                break;
            case SNSMessageIM:
                cell = [tableView dequeueReusableCellWithIdentifier:kIMCell];
                break;
            case SNSMessageRest:
                cell = [tableView dequeueReusableCellWithIdentifier:kRestCell];
                break;
            case SNSMEssageSchedule:
                cell = [tableView dequeueReusableCellWithIdentifier:kIMCell];
                break;
            case SNSMessageCookMenu:
                cell = [tableView dequeueReusableCellWithIdentifier:kIMCell];
                break;
            default:
                cell = [tableView dequeueReusableCellWithIdentifier:kIMCell];
                break;
        }
        
        cell.data = self.data[kMessageKey][indexPath.row];
        
        return cell;
        
        
    }else{
        SNSPostViewCell *cell;
        if ([self.data[kPostKey]count] == 0) {
            //demo data
            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellShort forIndexPath:indexPath];
            
        }else{
            
            SNSPostModel *data = self.data[kPostKey][indexPath.row];
            
            switch (data.type) {
                case SNSPostText:
                {
                    switch ([self checkPostType:data]) {
                        case SNSPostShort:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellText forIndexPath:indexPath];
                            break;
                        case SNSPostPlusOne:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellTextPlusOne forIndexPath:indexPath];
                            break;
                        case SNSPostNoPlusOne:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellTextComment forIndexPath:indexPath];
                            break;
                        case SNSPostAll:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellTextAll forIndexPath:indexPath];
                            break;
                    }
                }
                    break;
                case SNSPostPhoto:
                {
                    switch ([self checkPostType:data]) {
                        case SNSPostShort:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellShort forIndexPath:indexPath];
                            break;
                        case SNSPostPlusOne:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellPlusOne forIndexPath:indexPath];
                            break;
                        case SNSPostNoPlusOne:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellNoPlusOne forIndexPath:indexPath];
                            break;
                        case SNSPostAll:
                            cell = [tableView dequeueReusableCellWithIdentifier:kPostCellAll forIndexPath:indexPath];
                            break;
                    }
                }
                    break;
                case SNSPostVoice:
                {
                    NSLog(@"error sns data voice");
                }
                    break;
            }
            
            
            
            cell.data = data;
            [cell setNeedsUpdateConstraints];
//            [cell layoutIfNeeded];
            
            cell.viewController = self;
        }
        cell.delegate = self;
        return cell;
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        return 44;
    } else {
        if ([self.data[kPostKey] count] == 0) {
            //默认
            return 470;
        }
        
        
        SNSPostModel *cellData = _data[kPostKey][indexPath.row];
        
        NSUInteger offsetHeight = 20;
        switch (cellData.type) {
            case SNSPostText:
            {
                CGSize size;
                CGSize textViewSize;
                
                switch ([self checkPostType:cellData]) {
                    case SNSPostShort:
                        self.prototypeCellText.data = cellData;
                        size = [self.prototypeCellText.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                        return size.height+1 +offsetHeight;
                    break;
                    case SNSPostPlusOne:
                        self.prototypeCellTextPlusOne.data = cellData;
                        size = [self.prototypeCellTextPlusOne.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                        NSLog(@"data = %@ size.height = %f, textView.height = %f",cellData.content, size.height, textViewSize.height);
                        return size.height+1 +offsetHeight;
                    break;
                    case SNSPostNoPlusOne:
                        self.prototypeCellTextComment.data = cellData;
                        size = [self.prototypeCellTextComment.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                        textViewSize = [self.prototypeCellTextComment.commentTextView sizeThatFits:CGSizeMake(self.prototypeCellTextComment.commentTextView.frame.size.width, FLT_MAX)];
                        NSLog(@"data = %@ size.height = %f, textView.height = %f",cellData.content, size.height, textViewSize.height);
                        return size.height +1 +offsetHeight;
                    break;
                    case SNSPostAll:
                        self.prototypeCellTextAll.data = cellData;
                        size = [self.prototypeCellTextAll.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                        textViewSize = [self.prototypeCellTextAll.commentTextView sizeThatFits:CGSizeMake(self.prototypeCellTextAll.commentTextView.frame.size.width, FLT_MAX)];
                        NSLog(@"size.height = %f, textView.height = %f", size.height, textViewSize.height);
                        NSLog(@"data = %@ size.height = %f, textView.height = %f",cellData.content, size.height, textViewSize.height);
                        return size.height +1 +offsetHeight;
                        
                    break;
                }
                
                
                NSLog(@"text cell size height is %f",size.height);
                
            }
                break;
            case SNSPostPhoto:
            {
                switch ([self checkPostType:cellData]) {
                    case SNSPostShort:
                        return 453+1;
                        break;
                    case SNSPostPlusOne:
                        return 502+1;
                        break;
                    case SNSPostNoPlusOne:{
                        self.prototypeCellNoPlusOne.data = cellData;
//                        CGSize size = [self.prototypeCellNoPlusOne.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                        //                UITextView *commentView = self.prototypeCellNoPlusOne.commentTextView;
                        //                NSLog(@"comment content = %@", commentView.text);
                        CGSize textViewSize = [self.prototypeCellNoPlusOne.commentTextView sizeThatFits:CGSizeMake(self.prototypeCellNoPlusOne.commentTextView.frame.size.width, FLT_MAX)];
                        //                NSLog(@"fitting noPlusOne size = %f", size.height+textViewSize.height);
                        
                        return 461+textViewSize.height+1 +offsetHeight;
                    }
                        break;
                    case SNSPostAll:{
                        self.prototypeCell.data = cellData;
//                        [self.prototypeCell setNeedsUpdateConstraints ];
//                        
//                        [self.prototypeCell updateConstraintsIfNeeded ];
//                        
//                        [self.prototypeCell. contentView setNeedsLayout ];
//                        
//                        [self.prototypeCell. contentView layoutIfNeeded ];
                        
                        CGSize size = [self.prototypeCell.contentView systemLayoutSizeFittingSize:UILayoutFittingCompressedSize];
                            CGSize textViewSize = [self.prototypeCell.commentTextView sizeThatFits:CGSizeMake(self.prototypeCell.commentTextView.frame.size.width, FLT_MAX)];
                        NSLog(@"fram size = %@", NSStringFromCGRect(self.prototypeCell.commentTextView.frame));
                            NSLog(@"layoutSize all size = %@", NSStringFromCGSize(size));
                            NSLog(@"textViewSize all size = %@", NSStringFromCGSize(textViewSize));
                        NSUInteger height = size.height+textViewSize.height;
                        NSLog(@"comment = %@ \n height = %d",self.prototypeCell.commentTextView.text, height);
                        return 501+textViewSize.height+1 +offsetHeight;
                    }
                        break;
                }
                
            }
                break;
                
            case SNSPostVoice:
            {
                NSLog(@"error sns data voice data %@", cellData);
                
            }
                break;
        }
        
    }
    return 0;
}


-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        return YES;
    }else {
        return NO;
    }
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.section == 0) {
        NSDictionary *data = _data[kMessageKey][indexPath.row];
        switch ([data[@"type"] intValue]) {
            case SNSMessageNotice:
                [self.mm_drawerController.leftDrawerViewController performSegueWithIdentifier:@"SegueToNotice" sender:self];
                break;
            case SNSMessageCheckOn:
                [self.mm_drawerController.leftDrawerViewController performSegueWithIdentifier:@"toNavCheckOnParent" sender:self];
                break;
            case SNSMessageRest:
                [self.mm_drawerController.leftDrawerViewController performSegueWithIdentifier:@"toRestApplicationList" sender:self];
                break;
            case SNSMessageScore:
                [self.mm_drawerController.leftDrawerViewController performSegueWithIdentifier:@"toScoreParent" sender:self];
                break;
            case SNSMessageIM:
                [(MenuViewController *)self.mm_drawerController.leftDrawerViewController toChatAction:self];
                break;
        }
        
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
}


#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    
    //    NSLog(@"postID =  %@", postId);
    if ([segue.identifier isEqualToString:@"toCommentView"]) {
        NSString *postId = [NSString stringWithString:sender];
        UINavigationController *destViewController = segue.destinationViewController;
        SNSCommentViewController *root = destViewController.viewControllers[0];
        root.postId = postId;
        root.delegate = self;
        
    }else if ([segue.identifier isEqualToString:@"toEditPhotoSNS"]){
        UINavigationController *destViewController = segue.destinationViewController;
        SNSPhotoFilterViewController *root = destViewController.viewControllers[0];
        root.image = sender;
        root.tempDelegate = self;
        
    }else if ([segue.identifier isEqualToString:@"toSendTextSNS"]){
        UINavigationController *destViewController = segue.destinationViewController;
        SNSTextViewController *root = destViewController.viewControllers[0];
        root.delegate = self;
    }
}


- (IBAction)selectPhotoAction:(id)sender {
    UIActionSheet *actionSheet;
    NSString *cancelButtonTitle = NSLocalizedString(@"取消", nil);
    NSString *destructiveButtonTitle = NSLocalizedString(@"拍照", nil);
    NSString *otherButtonTitle = NSLocalizedString(@"从相册中选取", nil);
    NSString *otherTextButtonTitle = NSLocalizedString(@"文字内容", nil);
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:destructiveButtonTitle otherButtonTitles:otherButtonTitle, otherTextButtonTitle,nil];
    }else{
        actionSheet = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:cancelButtonTitle destructiveButtonTitle:otherButtonTitle otherButtonTitles:otherTextButtonTitle, nil];
    }
    [actionSheet showInView:self.view];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    NSLog(@"button index %zd", buttonIndex);
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        if (buttonIndex == 0) {
            // 拍照
            
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypeCamera;
//            [self.navigationController pushViewController:picker animated:YES];
            [self presentViewController:picker animated:YES completion:nil];
        }else if (buttonIndex == 1){
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
//            [self.navigationController pushViewController:picker animated:YES];
            [self presentViewController:picker animated:YES completion:nil];
        }else if(buttonIndex == 2){
            //文字消息
            [self performSegueWithIdentifier:@"toSendTextSNS" sender:nil];
        }
    }else{
        if (buttonIndex == 0) {
            // 从相册中选取
            UIImagePickerController *picker = [[UIImagePickerController alloc]init];
            picker.delegate =self;
            picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            [self presentViewController:picker animated:YES completion:nil];
        }else if(buttonIndex == 1){
            //文字消息
            [self performSegueWithIdentifier:@"toSendTextSNS" sender:nil];
        }
    }
    
}

#pragma mark - UIImagePickerControllerDelegate
-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info{
    NSLog(@"pick a photo");
    //    UIImage *image =  [info objectForKey:UIImagePickerControllerOriginalImage];
    NSURL *assetURL = [info objectForKey:UIImagePickerControllerReferenceURL];
    
    
    [picker dismissViewControllerAnimated:NO completion:^{
        NSLog(@"dismissViewControllerAnimated imagePicker");
        ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
        [library assetForURL:assetURL resultBlock:^(ALAsset *asset) {
            UIImage *preview = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
            
//            SNSCropImageViewController *imageEditor = [[UIStoryboard storyboardWithName:@"Main" bundle:nil]instantiateViewControllerWithIdentifier:kCropPhotoViewId];

            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil];
            
            
//            imageEditor.customRect = CGRectMake(0, 0, 300, 300);
            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                [self dismissViewControllerAnimated:NO completion:nil];
                if (!canceled) {
                    //self.userPhoto = editedImage;
                    [self performSegueWithIdentifier:@"toEditPhotoSNS" sender:[self reSizePhoto:editedImage newHeightSize:kCropPhotoSize]];
                    
//                    [self sendPhotoMessages:editedImage preViewPhoto: preViewPhoto];
                }
            };
            [self presentViewController:imageEditor animated:YES completion:nil];
        } failureBlock:^(NSError *error) {
            NSLog(@"error occour when read preview photo %@", error);
            
            SNSCropImageViewController *imageEditor = [[SNSCropImageViewController alloc] initWithNibName:@"SNSCropImage" bundle:nil];
            
            imageEditor.cropRect = CGRectMake(0, 0, [[UIScreen mainScreen] bounds].size.width, [[UIScreen mainScreen] bounds].size.width);

            
            imageEditor.sourceImage = [info objectForKey:UIImagePickerControllerOriginalImage];
            //            imageEditor.previewImage = preview;
            
            imageEditor.doneCallback = ^(UIImage *editedImage, BOOL canceled){
                NSLog(@"imageEditor.doneCallback");
                if (!canceled) {
                    //                    self.userPhoto = editedImage;

                    
                    [self performSegueWithIdentifier:@"toEditPhotoSNS" sender:[self reSizePhoto:editedImage newHeightSize:kCropPhotoSize]];
                    
//                    [self sendPhotoMessages:editedImage preViewPhoto: preViewPhoto];
                }
                
                [self dismissViewControllerAnimated:NO completion:nil];
            };
            [self presentViewController:imageEditor animated:NO completion:nil];
        }];
        
        
    }];
    
}

- (UIImage *)reSizePhoto:(UIImage *)image newHeightSize:(CGFloat)height{
    
    CGFloat newWidth = image.size.width/image.size.height * height;
    CGSize size = CGSizeMake(newWidth, height);
    
    UIGraphicsBeginImageContextWithOptions(size, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, size.width, size.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}

//FIX: 上传的缩略图好像有点大


#pragma mark - make a animetor pointer image
-(UIImageView *)makePointerView:(CGPoint)point {
    //test pointer anime
    UIImageView *pointerView = [[UIImageView alloc]initWithFrame:CGRectMake(point.x, point.y, 50, 50)];
    static NSMutableArray *shareImages = nil;
    static dispatch_once_t oncePredicate;
    dispatch_once(&oncePredicate, ^{
        shareImages = [NSMutableArray array];
        for (int i = 11; i <= 43; i ++)
        {
            //将要播放的图片加入数组
            [shareImages addObject:[UIImage imageNamed:[NSString stringWithFormat:@"圆点00%02d.png", i]]];
            
        }
    });
    
    pointerView.animationImages = shareImages;
    pointerView.animationDuration = 1.7;  //播放一次动画时长
    pointerView.animationRepeatCount = -1; // 播放次数，-1 无限
    [self.view addSubview:pointerView];
    [pointerView startAnimating];
    
    return pointerView;
}




- (void)openPhoto:(NSURL *)url{
    //    NSMutableArray *photos = [NSMutableArray array];
    
    displayPhoto = [MWPhoto photoWithURL:url];
    
    MWPhotoBrowser *browser = [[MWPhotoBrowser alloc]initWithDelegate:self];
    browser.displayActionButton = YES; // Show action button to allow sharing, copying, etc (defaults to YES)
    browser.displayNavArrows = NO; // Whether to display left and right nav arrows on toolbar (defaults to NO)
    browser.displaySelectionButtons = NO; // Whether selection buttons are shown on each image (defaults to NO)
    browser.zoomPhotosToFill = YES; // Images that almost fill the screen will be initially zoomed to fill (defaults to YES)
    browser.alwaysShowControls = NO; // Allows to control whether the bars and controls are always visible or whether they fade away to show the photo full (defaults to NO)
    browser.enableGrid = YES; // Whether to allow the viewing of all the photo thumbnails on a grid (defaults to YES)
    browser.startOnGrid = NO; // Whether to start on the grid of thumbnails instead of the first photo (defaults to NO)
    //    browser.wantsFullScreenLayout = YES; // iOS 5 & 6 only: Decide if you want the photo browser full screen, i.e. whether the status bar is affected (defaults to YES)
    
    [self.navigationController pushViewController:browser animated:YES];
}


-(SNSDisplayType)checkPostType:(SNSPostModel *)data{
    
//    NSLog(@"comments = %@", data);
    
    if (data.comments && data.plusOneList) {
        return SNSPostAll;
    }
    else if (data.comments && !data.plusOneList ) {
        return SNSPostNoPlusOne;
    }
    else if (!data.comments && data.plusOneList ) {
        return SNSPostPlusOne;
    }
    else {
        return SNSPostShort;
    }
}

#pragma mark - MWPhotoBrowserDelegate
- (NSUInteger)numberOfPhotosInPhotoBrowser:(MWPhotoBrowser *)photoBrowser{
    return 1;
}
- (id <MWPhoto>)photoBrowser:(MWPhotoBrowser *)photoBrowser photoAtIndex:(NSUInteger)index{
    return displayPhoto;
}


#pragma mark setter & getter
-(NSDictionary *)data{
    if (!_data) {
        _data = @{kMessageKey:[NSMutableArray array], kPostKey:[NSMutableArray array]};
    }
    
    return _data;
}

#pragma mark - SNSPostViewDelegate
-(void)didTouchedPlusOne{

    [self loadSNSData:0 :[self.data[kPostKey] count] snsType:SNSTypeAll isBackground:YES goTop:NO];
}

#pragma mark - SNSCommentViewControllerDelegate
-(void)didFinishedSNSComment{
    [self loadSNSData:0 :[self.data[kPostKey] count] snsType:SNSTypeAll isBackground:YES goTop:NO];
}

#pragma mark - SNSSendPostDelegate
-(void)didSendSNSPost{
    [self loadSNSData:0 :kMaxReturnCount snsType:SNSTypeAll isBackground:YES goTop:YES];
}
@end
